#include "CharacterEntity.hpp"

CharacterEntity::CharacterEntity(){
	init(0, 0, 0, 0);
}

CharacterEntity::CharacterEntity(Map* m, float x, float y, byte dir){
	init(m, x, y, dir);
}

void CharacterEntity::init(Map* m, float x, float y, byte dir){

	cWidth = 20;
    cHeight = 22;
    cxOffset = 6;
    cyOffset = 10;

	map = m;
	direction = dir;
	Entity::x = x;
	Entity::y = y;
	maxVelocityX = maxVelocityY = 2;
	velocityX = velocityY = 0;
	acceleration = 0.1;
}

void CharacterEntity::setMap(Map* m){
    map = m;
}

void CharacterEntity::setLocation(float x, float y, byte dir){
    this->x = x;
    this->y = y;
    direction = dir;
}

void CharacterEntity::move(){
    moveX();
    moveY();
}

void CharacterEntity::moveX(){
    
    //Backup current location and move character.
	float tX = x;
	Entity::moveX();
    
    //Get collision box location
    float cX = x + cxOffset;

    unsigned short tileX = 0;
    //Check horizontal movement collision.
	if(velocityX){
		if(velocityX < 0){
			tileX = (unsigned short)(cX/32);
			if(tileX >= map->width || map->getTile(tileX, (y + cyOffset)/32).properties & Tile::t_BlockRight ||
				map->getTile(tileX, (y + cyOffset+cHeight)/32).properties & Tile::t_BlockRight){
				x = tX;
				velocityX = 0;
			}
			
		}else{
			tileX = (unsigned short)(cX + cWidth)/32;
			if(tileX >= map->width || map->getTile(tileX, (y + cyOffset)/32).properties & Tile::t_BlockLeft ||
				map->getTile(tileX, (y + cyOffset+cHeight)/32).properties & Tile::t_BlockLeft){
				x = tX;
				velocityX = 0;
			}
		}
	}
}

void CharacterEntity::moveY(){
    
    //Backup current location and move character.
	float tY = y;
	Entity::moveY();
    
    //Get collision box location
    float cY = y + cyOffset;
    
    unsigned short tileY = 0;
    //Check vertical movement collision
	if(velocityY){
		if(velocityY < 0){
			tileY = (unsigned short)(cY/32);
			if(tileY >= map->height || map->getTile((int)(x + cxOffset)/32, tileY).properties & Tile::t_BlockTop ||
				map->getTile((int)(x + cxOffset+cWidth)/32, tileY).properties & Tile::t_BlockTop){
				y = tY;
				velocityY = 0;
			}
			
		}else{
			tileY = (unsigned short)((cY+cHeight)/32);
			if(tileY >= map->height || map->getTile((int)(x + cxOffset)/32, tileY).properties & Tile::t_BlockBottom ||
				map->getTile((int)(x + cxOffset+cWidth)/32, tileY).properties & Tile::t_BlockBottom){
				y = tY;
				velocityY = 0;
			}
		}
	}
}

void CharacterEntity::update(){

}